package cn.netjava.dao;

import cn.netjava.connect.Connection;
import cn.netjava.pojo.Article;
import cn.netjava.pojo.UserInfo;

public class UserDao {

	public void insertUser(UserInfo user) {
		String sql = "insert into userinfo(userName,userPwd) values(?,?)";
		// 取得数据库的连接对象
		java.sql.Connection connec = Connection.getConnec();
		try {
			// 取得预编译对象
			java.sql.PreparedStatement ps = connec.prepareStatement(sql);
			// 给参数赋值
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getUserPwd());
			// 执行保存
			ps.executeUpdate();
			System.out.println("用户对象保存成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 判断用户名和密码是否正确
	public boolean checkUser(UserInfo user) {
		String sql = "select *from userinfo where userName=? and userPwd=?";
		// 取得数据库的连接对象
		java.sql.Connection connec = Connection.getConnec();
		try {
			// 取得预编译对象
			java.sql.PreparedStatement ps = connec.prepareStatement(sql);
			// 给参数赋值
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getUserPwd());
			// 查找用户
			java.sql.ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	public boolean checkUserName(UserInfo user) {
		String sql = "select *from userinfo where userName=?";
		// 取得数据库的连接对象
		java.sql.Connection connec = Connection.getConnec();
		try {
			// 取得预编译对象
			java.sql.PreparedStatement ps = connec.prepareStatement(sql);
			// 给参数赋值
			ps.setString(1, user.getUserName());
			// 查找用户
			java.sql.ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	/*
	 * 2.将用户所写文章保存到数据库
	 */
	public void AddAtricle(Article article) {
		try {
			// 1.写sql
			String sql = "insert into article(user_id,title,content)"
					+ " values(?,?,?)";
			// 2.取得连接对象
			java.sql.Connection connec = Connection.getConnec();
			// 3.得到预编译对象
			java.sql.PreparedStatement ps = connec.prepareStatement(sql);
			// 4.给预编译对象赋值
			ps.setInt(1, article.getId_user());
			ps.setString(2, article.getTitle());
			ps.setString(3, article.getContent());
			System.out.print("id为"+article.getId_user()+"标题"+article.getTitle()+"内容"+article.getContent());
            // 5.加为批处理
			ps.addBatch();
			// 6.执行批处理
			ps.executeBatch();
		} catch (Exception ef) {
			ef.printStackTrace();
		}
	}
	/**
	 * 7.根据文章ID，删除文章对象
	 * @param id:文章ID
	 */
	public void deleteArticle(int id){
		try{
		//1.写sql
		String sql="delete from article where id=?";
		//2.取得连接对象
		java.sql.Connection connec = Connection.getConnec();
		//3.得到预编译对象
		java.sql.PreparedStatement ps=connec.prepareStatement(sql);
		//4.赋值
		ps.setInt(1, id);
		//5.执行变化
		ps.executeUpdate();
		}catch(Exception ef){
			ef.printStackTrace();
		}
		
	}
}
